package cn.edu.nuaa.controller;


import cn.edu.nuaa.mapper.ResourceMapper;
import cn.edu.nuaa.model.Resource;
import cn.edu.nuaa.utils.Md5Util;
import cn.edu.nuaa.utils.MybatisUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.sql.Date;
import java.util.List;

@RequestMapping(value = "/file")
@Controller
public class FileController {
    SqlSession sqlSession = MybatisUtils.getSession();
    ResourceMapper resourceMapper = sqlSession.getMapper(ResourceMapper.class);
    private String filePath = "/mnt/dev/code/java/java2ee/login/file";

    @RequestMapping(value = "/page")
    public ModelAndView filePage() {
        ModelAndView modelAndView = new ModelAndView("file");
        List<Resource> resourceList = resourceMapper.selectAll();
        modelAndView.addObject("resourceList", resourceList);
        return modelAndView;
    }

    @RequestMapping(value = "/upload", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String name = filePath + "/" + originalFilename;
            File file1 = new File(name);
            int suffixNum = 1;
            while (file1.exists()) {
                String baseName = FilenameUtils.getBaseName(originalFilename); //获取没有扩展名的文件名
                String extension = FilenameUtils.getExtension(originalFilename); //获取扩展名
                originalFilename = baseName + "_" + suffixNum + "." + extension; //添加后缀数并重新生成文件名
                name = filePath + "/" + originalFilename;
                file1 = new File(name); //检查是否仍存在同名文件
                suffixNum++;
            }
            file.transferTo(file1);
            String calculateMD5 = Md5Util.calculateMD5(file1);
            List<Resource> resourceList = resourceMapper.selectResourceByMd5(calculateMD5);
            if (resourceList.size() != 0) {
                Resource resource = new Resource();
                resource.setName(originalFilename);
                resource.setMd5(resourceList.get(0).getMd5());
                resource.setPath(resourceList.get(0).getPath());
                resource.setCreateTime(new Date(System.currentTimeMillis()));
                resourceMapper.insertResource(resource);
                file1.delete();
            } else {
                Resource resource = new Resource();
                resource.setName(originalFilename);
                resource.setMd5(calculateMD5);
                resource.setPath(name);
                resource.setCreateTime(new Date(System.currentTimeMillis()));
                resourceMapper.insertResource(resource);
            }
            sqlSession.commit();
        }
        ModelAndView modelAndView = new ModelAndView("file");
        List<Resource> resourceList = resourceMapper.selectAll();
        modelAndView.addObject("resourceList", resourceList);
        return modelAndView;
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> fileDownload(String filename) throws Exception {
        Resource resource = resourceMapper.selectResourceByName(filename);
        String path = resource.getPath();// 下载文件所在路径
        File file = new File(path); // 创建文件对象
        HttpHeaders headers = new HttpHeaders(); // 设置消息头
        headers.setContentDispositionFormData("attachment", filename);// 打开文件
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 下载返回的文件数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.OK); // 使用ResponseEntity对象封装返回下载数据

    }
}
